package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.contrarywind.adapter.WheelAdapter;
import com.contrarywind.listener.OnItemSelectedListener;
import com.contrarywind.view.WheelView;
import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.ColorAdapter;
import flc.ast.bean.CommemorateBean;
import flc.ast.bean.MyColorBean;
import flc.ast.bean.NoteBean;
import flc.ast.databinding.ActivityCommemorateBinding;
import flc.ast.utils.AppSpUtils;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.StkPermissionHelper;

public class CommemorateActivity extends BaseAc<ActivityCommemorateBinding> {

    public static CommemorateBean commemorateBean;
    public static int itemPosition;
    private ColorAdapter colorAdapter;
    private int oldPosition;
    private int selColor;
    private String path = "";
    private Dialog myTargetDateDialog;
    private WheelView wheelView1, wheelView2, wheelView3;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");

    @Override
    protected int onCreate() {
        return R.layout.activity_commemorate;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(this, mDataBinding.event5Container);

        mDataBinding.ivCommemorateBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivCommemorateComplete.setOnClickListener(this);
        mDataBinding.tvDate.setOnClickListener(this);
        mDataBinding.tvUploadCover.setOnClickListener(this);
        mDataBinding.ivCoverImg.setOnClickListener(this);
        mDataBinding.ivCoverDelete.setOnClickListener(this);

        mDataBinding.rvColorList.setLayoutManager(new GridLayoutManager(mContext, 5));
        colorAdapter = new ColorAdapter();
        mDataBinding.rvColorList.setAdapter(colorAdapter);
        colorAdapter.setOnItemClickListener(this);

        //选择日期弹框
        selDateDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivCommemorateComplete://完成
                if (commemorateBean == null) {
                    save();
                } else {
                    change();
                }
                break;
            case R.id.tvDate://目标日
                myTargetDateDialog.show();
                break;
            case R.id.tvUploadCover://上传封面
            case R.id.ivCoverImg:
                getPermission();
                break;
            case R.id.ivCoverDelete://删除封面
                path = "";
                mDataBinding.tvUploadCover.setVisibility(View.VISIBLE);
                mDataBinding.ivCoverImg.setVisibility(View.GONE);
                mDataBinding.ivCoverDelete.setVisibility(View.GONE);
                break;
            //选择日期弹框
            case R.id.tvDialogTargetDateCancel://取消
                myTargetDateDialog.dismiss();
                break;
            case R.id.tvDialogTargetDateRight://确定
                myTargetDateDialog.dismiss();
                int year = wheelView1.getCurrentItem() + 1980;
                int moon = wheelView2.getCurrentItem() + 1;
                int day = wheelView3.getCurrentItem() + 1;
                String selDate = year + "-" + (moon < 10 ? "0" + moon : moon) + "-" + (day < 10 ? "0" + day : day + "") + " ";
                mDataBinding.tvDate.setText(selDate);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        colorAdapter.getItem(oldPosition).setSelect(false);
        colorAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        colorAdapter.getItem(position).setSelect(true);
        colorAdapter.notifyItemChanged(position);
        selColor = Color.parseColor(colorAdapter.getItem(position).getColor());
    }

    @Override
    protected void initData() {
        List<MyColorBean> listColor = new ArrayList<>();
        listColor.add(new MyColorBean("#EF4165", false));
        listColor.add(new MyColorBean("#FF9A9A", false));
        listColor.add(new MyColorBean("#FDA723", false));
        listColor.add(new MyColorBean("#35D979", false));
        listColor.add(new MyColorBean("#45B5FA", false));
        listColor.add(new MyColorBean("#7DA0FF", false));
        listColor.add(new MyColorBean("#BE7DFF", false));
        listColor.add(new MyColorBean("#FF7DF9", false));
        listColor.add(new MyColorBean("#8185AC", false));
        if (commemorateBean == null) {
            selColor = Color.parseColor(listColor.get(0).getColor());
            oldPosition = 0;
        } else {
            for (int i = 0; i < listColor.size(); i++) {
                if (Color.parseColor(listColor.get(i).getColor()) == commemorateBean.getColor()) {
                    selColor = Color.parseColor(listColor.get(i).getColor());
                    oldPosition = i;
                }
            }
            mDataBinding.etTitle.setText(commemorateBean.getTitle());
            mDataBinding.tvDate.setText(commemorateBean.getDate());
            path = commemorateBean.getPath();
            if (path.isEmpty()) {
                mDataBinding.tvUploadCover.setVisibility(View.VISIBLE);
                mDataBinding.ivCoverImg.setVisibility(View.GONE);
                mDataBinding.ivCoverDelete.setVisibility(View.GONE);
            } else {
                Glide.with(mContext).load(path).into(mDataBinding.ivCoverImg);
                mDataBinding.tvUploadCover.setVisibility(View.GONE);
                mDataBinding.ivCoverImg.setVisibility(View.VISIBLE);
                mDataBinding.ivCoverDelete.setVisibility(View.VISIBLE);
            }
        }
        listColor.get(oldPosition).setSelect(true);
        colorAdapter.setList(listColor);
    }

    private void save() {
        String title = mDataBinding.etTitle.getText().toString();
        String date = mDataBinding.tvDate.getText().toString();
        if (TextUtils.isEmpty(title)) {
            ToastUtils.showShort(getString(R.string.please_input_title));
            mDataBinding.etTitle.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(date)) {
            ToastUtils.showShort(getString(R.string.please_sel_target_date));
            return;
        }
        CommemorateBean bean = new CommemorateBean(title, date, selColor, path);
        List<CommemorateBean> listSp = AppSpUtils.getCommemorateList();
        if (listSp != null && listSp.size() > 0) {
            listSp.add(bean);
            Collections.sort(listSp, new Comparator<CommemorateBean>() {
                @Override
                public int compare(CommemorateBean o1, CommemorateBean o2) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    long today = TimeUtils.getNowMills();
                    long time1 = Math.abs(TimeUtils.string2Millis(o1.getDate(), format) - today);
                    long time2 = Math.abs(TimeUtils.string2Millis(o2.getDate(), format) - today);
                    return Long.compare(time1, time2);
                }
            });
            AppSpUtils.saveCommemorateList(listSp);
        } else {
            List<CommemorateBean> listSave = new ArrayList<>();
            listSave.add(bean);
            AppSpUtils.saveCommemorateList(listSave);
        }
        ToastUtils.showShort(getString(R.string.save_success));
        finish();
    }

    private void change() {
        String title = mDataBinding.etTitle.getText().toString();
        String date = mDataBinding.tvDate.getText().toString();
        if (TextUtils.isEmpty(title)) {
            ToastUtils.showShort(getString(R.string.please_input_title));
            mDataBinding.etTitle.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(date)) {
            ToastUtils.showShort(getString(R.string.please_sel_target_date));
            return;
        }
        List<CommemorateBean> listSp = AppSpUtils.getCommemorateList();
        listSp.get(itemPosition).setTitle(title);
        listSp.get(itemPosition).setDate(date);
        listSp.get(itemPosition).setColor(selColor);
        listSp.get(itemPosition).setPath(path);
        AppSpUtils.saveCommemorateList(listSp);
        ToastUtils.showShort(getString(R.string.save_success));
        finish();
    }

    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_picture_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getImage();
                    }
                }).request();
    }

    private void getImage() {
        PhotoSelectorBuilder.builder(this)
                .mode(PhotoConfig.Mode.PHOTO)
                .minCount(1)
                .maxCount(1)
                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                    @Override
                    public void onResult(List<SelectMediaEntity> data) {
                        ArrayList<String> pathList = new ArrayList<>();
                        for (SelectMediaEntity entity : data) {
                            pathList.add(entity.getTargetPath());
                        }
                        path = pathList.get(0);
                        Glide.with(mContext).load(path).into(mDataBinding.ivCoverImg);
                        mDataBinding.tvUploadCover.setVisibility(View.GONE);
                        mDataBinding.ivCoverImg.setVisibility(View.VISIBLE);
                        mDataBinding.ivCoverDelete.setVisibility(View.VISIBLE);
                    }
                });
    }

    //选择日期弹框
    private void selDateDialog() {
        myTargetDateDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_target_date, null);
        myTargetDateDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = myTargetDateDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lp.width = (int) (dm.widthPixels * 1);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogTargetDateCancel);
        TextView dialogRight = inflate.findViewById(R.id.tvDialogTargetDateRight);
        wheelView1 = inflate.findViewById(R.id.wheel_view1);
        wheelView2 = inflate.findViewById(R.id.wheel_view2);
        wheelView3 = inflate.findViewById(R.id.wheel_view3);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
        wheelView1.setDividerColor(Color.parseColor("#FFEBED"));
        wheelView1.setTextColorCenter(Color.parseColor("#191919"));
        wheelView1.setLineSpacingMultiplier(2.5f);
        wheelView1.setDividerType(WheelView.DividerType.WRAP);
        wheelView1.setCurrentItem(43);
        wheelView1.setItemsVisibleCount(5);
        wheelView1.setCyclic(true);
        wheelView1.setTextSize(16);
        wheelView2.setDividerColor(Color.parseColor("#FFEBED"));
        wheelView2.setTextColorCenter(Color.parseColor("#191919"));
        wheelView2.setLineSpacingMultiplier(2.5f);
        wheelView2.setDividerType(WheelView.DividerType.WRAP);
        wheelView2.setCurrentItem(0);
        wheelView2.setItemsVisibleCount(5);
        wheelView2.setCyclic(true);
        wheelView2.setTextSize(16);
        wheelView3.setDividerColor(Color.parseColor("#FFEBED"));
        wheelView3.setTextColorCenter(Color.parseColor("#191919"));
        wheelView3.setLineSpacingMultiplier(2.5f);
        wheelView3.setDividerType(WheelView.DividerType.WRAP);
        wheelView3.setCurrentItem(0);
        wheelView3.setItemsVisibleCount(5);
        wheelView3.setCyclic(true);
        wheelView3.setTextSize(16);
        //设置滚轮数据
        List<String> listYear = new ArrayList<>();//年 1980-2040
        for (int i = 0; i < 61; i++) {
            listYear.add(String.valueOf(1980 + i));
        }
        List<String> listMonth = new ArrayList<>();//月 12
        for (int i = 0; i < 12; i++) {
            listMonth.add(String.valueOf((i + 1) < 10 ? "0" + (i + 1) : i + 1));
        }
        WheelAdapter adapter1 = new ArrayWheelAdapter(listYear);
        wheelView1.setAdapter(adapter1);
        WheelAdapter adapter2 = new ArrayWheelAdapter(listMonth);
        wheelView2.setAdapter(adapter2);
        setDayDate(31);//日 默认显示1月 共31天

        //监听月份滚动选择
        wheelView2.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                index = index + 1;
                if (index == 1 || index == 3 || index == 5 || index == 7 || index == 8 || index == 10 || index == 12) {
                    //大月31天
                    setDayDate(31);
                } else if (index == 2) {
                    //2月判断是闰(29)还是平(28)
                    if (TimeUtils.isLeapYear(TimeUtils.getNowString(format), format)) {
                        setDayDate(29);
                    } else {
                        setDayDate(28);
                    }
                } else {
                    //小月30天
                    setDayDate(30);
                }
            }
        });
        //滚动到对应日期
        String date = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
        String[] split = date.split("-");
        int year = Integer.parseInt(split[0]);//年
        int moon = Integer.parseInt(split[1]);//月
        int day = Integer.parseInt(split[2]);//日
        wheelView1.setCurrentItem(year - 1980);
        wheelView2.setCurrentItem(moon - 1);
        wheelView3.setCurrentItem(day - 1);
    }

    //设置天
    private void setDayDate(int num) {
        List<String> listDay = new ArrayList<>();//日 默认显示1月31天
        for (int i = 0; i < num; i++) {
            listDay.add(String.valueOf((i + 1) < 10 ? "0" + (i + 1) : i + 1));
        }
        WheelAdapter adapter3 = new ArrayWheelAdapter(listDay);
        wheelView3.setAdapter(adapter3);
    }

}